package cn.lxg.controller;


import cn.lxg.dao.entity.Lottery;
import cn.lxg.dao.mapper.LotteryMapper;
import cn.lxg.dao.service.ILotteryService;
import cn.lxg.rpc.LotteryRpc;
import cn.lxg.utils.LotteryBallUtils;
import cn.lxg.utils.LotteryUtils;
import cn.lxg.utils.RangeUtil;
import cn.lxg.vo.LotteryVo;
import cn.lxg.vo.WinLotteryVo;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.IoUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import org.jsoup.Connection;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.*;
import java.util.stream.Collectors;


@RestController
@RequestMapping(value = "lottery")
public class LotteryController {


    @Autowired
    private ILotteryService lotteryServiceImpl;

    @Autowired
    private LotteryMapper lotteryMapper;

    @Autowired
    private LotteryBallUtils lotteryBallUtils;

    @Autowired
    @Qualifier(value = "myAsync")
    private ThreadPoolTaskExecutor myAsync;


    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @GetMapping("/getData")
    private void getData() throws InterruptedException {
        LambdaQueryWrapper<Lottery> wrapper = new LambdaQueryWrapper<>();
        wrapper.last("order by code desc");
        //获取所有数据
        List<Lottery> lotteries = lotteryServiceImpl.list(wrapper);
//        最常出现的聚合范围 小——到大
        List<Integer> maxAndMinRange = RangeUtil.getMostFrequentNumberRange(lotteries.stream().map(Lottery::getTotal).collect(Collectors.toList()));

        WinLotteryVo result = null;
        int queryPeriod = 500;

        // 获取最近同周排查
        List<Lottery> sameWeek = lotteryServiceImpl.getLatelySizeBySameWeek(queryPeriod);
        //获取同天排查
        List<Lottery> sameDay = lotteryServiceImpl.getLatelySizeBySameDay(queryPeriod);
        //获取同期排查
        List<Lottery> samePeriod = lotteryServiceImpl.getLatelySizeBySamePeriod(queryPeriod);
        //直接获取最近排查
        List<Lottery> latelyDay = lotteryServiceImpl.getLatelySizeByDay(queryPeriod);


        //直接获取最近排查
        List<Lottery> thirtyByDay = lotteryServiceImpl.getLatelySizeByDay(5);
        while (true) {
            List<Integer> redCannotAppearNum = new ArrayList<>(lotteryServiceImpl.getAllRedList(sameWeek));
            redCannotAppearNum.addAll(lotteryServiceImpl.getAllRedList(sameDay));
            redCannotAppearNum.addAll(lotteryServiceImpl.getAllRedList(samePeriod));
            redCannotAppearNum.addAll(lotteryServiceImpl.getAllRedList(latelyDay));

            List<Integer> blueCannotAppearNum = new ArrayList<>(lotteryServiceImpl.getAllBlueList(sameWeek));
            redCannotAppearNum.addAll(lotteryServiceImpl.getAllBlueList(sameDay));
            redCannotAppearNum.addAll(lotteryServiceImpl.getAllBlueList(samePeriod));
            redCannotAppearNum.addAll(lotteryServiceImpl.getAllBlueList(latelyDay));

            Set<Integer> redCannotNumByLaterAndAllHistory = LotteryUtils.getCannotNumByLaterAndAllHistory(redCannotAppearNum, lotteryServiceImpl.getAllRedList(thirtyByDay));
            Set<Integer> blueCannotNumByLaterAndAllHistory = LotteryUtils.getCannotNumByLaterAndAllHistory(blueCannotAppearNum, lotteryServiceImpl.getAllBlueList(thirtyByDay));



            List<WinLotteryVo> historyWin = new ArrayList<>();
            for (Lottery lottery : lotteries) {
                WinLotteryVo winLotteryVo = new WinLotteryVo();
                List<Integer> redBall = new ArrayList<>();
                redBall.add(lottery.getRed1());
                redBall.add(lottery.getRed2());
                redBall.add(lottery.getRed3());
                redBall.add(lottery.getRed4());
                redBall.add(lottery.getRed5());
                redBall.add(lottery.getRed6());

                winLotteryVo.setCode(lottery.getCode());
                winLotteryVo.setRedBall(redBall);
                winLotteryVo.setBlueBall(lottery.getBlue());
                historyWin.add(winLotteryVo);
            }


            result = lotteryBallUtils.getWinLottery(redCannotNumByLaterAndAllHistory, blueCannotNumByLaterAndAllHistory, maxAndMinRange, historyWin);
            if (result != null) {
                break;
            }
        }
        redisTemplate.unlink(Objects.requireNonNull(redisTemplate.keys("redCount*")));
        System.out.println(result);
    }


    @GetMapping("/get")
    private void test() throws IOException {
        System.out.println("开始采集");
        int a = 1;
        while (true) {
            String url = "https://www.cwl.gov.cn/cwl_admin/front/cwlkj/search/kjxx/findDrawNotice?name=ssq&issueCount=&issueStart=&issueEnd=&dayStart=&dayEnd=&pageNo=" + a + "&pageSize=200&week=&systemType=PC";
//            Document doc = Jsoup.connect(url).get();
            Connection conn = Jsoup.connect(url);
            conn = Jsoup.connect(url);
            conn.header("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8");
            conn.header("Accept-Encoding", "gzip, deflate, sdch");
            conn.header("Accept-Language", "zh-CN,zh;q=0.8");
            conn.header("User-Agent", "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36");
//            Document doc = conn.get();
            Document doc = conn.followRedirects(true).get();//to follow redirects
            String str = doc.body().html();
            if (StringUtils.isBlank(str)) {
                return;
            }
            LotteryRpc bean = JSONUtil.toBean(str, LotteryRpc.class);
            if (bean.getState() != 0) {
                System.out.println("error:错误了");
                return;
            }
            if (CollectionUtil.isEmpty(bean.getResult())) {
                return;
            }
            List<Lottery> lotteries = new ArrayList<>();
            for (LotteryVo vo : bean.getResult()) {
                Lottery lottery = new Lottery();
                lottery.setCode(Long.valueOf(vo.getCode()));
                String s1 = vo.getDate().replaceAll("\\(", "").replaceAll("\\)", "").replaceAll("四", "");
                lottery.setDate(DateUtil.parseDate(s1));
                lottery.setRed(vo.getRed());
                String[] split = vo.getRed().split(",");
                lottery.setRed1(Integer.valueOf(split[0]));
                lottery.setRed2(Integer.valueOf(split[1]));
                lottery.setRed3(Integer.valueOf(split[2]));
                lottery.setRed4(Integer.valueOf(split[3]));
                lottery.setRed5(Integer.valueOf(split[4]));
                lottery.setRed6(Integer.valueOf(split[5]));
                lottery.setBlue(Integer.valueOf(vo.getBlue()));
                lottery.setTotal(lottery.getRed1() + lottery.getRed2() + lottery.getRed3() + lottery.getRed4() + lottery.getRed5() + lottery.getRed6() + lottery.getBlue());
            }
            //入库
            lotteryMapper.insertOrUpdate(lotteries);
            a++;
        }
    }

    @GetMapping("testFile")
    private void testFile() {
        String read = IoUtil.read(FileUtil.getInputStream("/Users/lixianggang/Desktop/ff.txt"), StandardCharsets.UTF_8);
        LotteryRpc bean = JSONUtil.toBean(read, LotteryRpc.class);
        List<Lottery> lotteries = new ArrayList<>();
        for (LotteryVo vo : bean.getResult()) {
            Lottery lottery = new Lottery();
            lottery.setCode(Long.valueOf(vo.getCode()));
            String s1 = vo.getDate().replaceAll("\\(", "").replaceAll("\\)", "").replaceAll(vo.getWeek(), "");
            lottery.setDate(DateUtil.parseDate(s1));
            lottery.setWeek(vo.getWeek());
            lottery.setRed(vo.getRed());
            String[] split = vo.getRed().split(",");
            lottery.setRed1(Integer.valueOf(split[0]));
            lottery.setRed2(Integer.valueOf(split[1]));
            lottery.setRed3(Integer.valueOf(split[2]));
            lottery.setRed4(Integer.valueOf(split[3]));
            lottery.setRed5(Integer.valueOf(split[4]));
            lottery.setRed6(Integer.valueOf(split[5]));
            lottery.setBlue(Integer.valueOf(vo.getBlue()));
            lottery.setTotal(lottery.getRed1() + lottery.getRed2() + lottery.getRed3() + lottery.getRed4() + lottery.getRed5() + lottery.getRed6() + lottery.getBlue());
            lotteries.add(lottery);
        }
        lotteryMapper.insertOrUpdate(lotteries);
    }


}
